<template>
  <div class="bank-card-validator">
    <div class="card">
      <div class="card-header bg-primary text-white">
        <h5 class="mb-0">
          <i class="fas fa-credit-card me-2"></i>
          银行卡信息验证
        </h5>
      </div>
      <div class="card-body">
        <form @submit.prevent="validateCard">
          <div class="row">
            <div class="col-md-6 mb-3">
              <label for="cardNumber" class="form-label">
                <strong>银行卡号：</strong>
                <span class="text-danger">*</span>
              </label>
              <input
                type="text"
                id="cardNumber"
                v-model="formData.cardNumber"
                class="form-control"
                :class="{
                  'is-valid': validation.cardNumberValid && formData.cardNumber,
                  'is-invalid': !validation.cardNumberValid && formData.cardNumber
                }"
                placeholder="请输入银行卡号"
                maxlength="23"
                @input="onCardNumberInput"
                @blur="validateCard"
              />
              <div class="form-text" v-if="detectedBank">
                <i class="fas fa-info-circle text-info"></i>
                检测到银行：{{ detectedBank }}
              </div>
              <div class="invalid-feedback" v-if="!validation.cardNumberValid && formData.cardNumber">
                银行卡号格式不正确，请检查输入
              </div>
            </div>
            
            <div class="col-md-6 mb-3">
              <label for="bankName" class="form-label">
                <strong>开户银行：</strong>
                <span class="text-danger">*</span>
              </label>
              <div class="input-group">
                <input
                  type="text"
                  id="bankName"
                  v-model="formData.bankName"
                  class="form-control"
                  :class="{
                    'is-valid': validation.bankNameValid && formData.bankName,
                    'is-invalid': !validation.bankNameValid && formData.bankName
                  }"
                  placeholder="请输入或选择银行名称"
                  list="bankList"
                  @input="onBankNameInput"
                  @blur="validateCard"
                />
                <button 
                  type="button" 
                  class="btn btn-outline-secondary dropdown-toggle" 
                  data-bs-toggle="dropdown"
                  aria-expanded="false"
                >
                  <i class="fas fa-chevron-down"></i>
                </button>
                <ul class="dropdown-menu dropdown-menu-end">
                  <li v-for="bank in supportedBanks" :key="bank">
                    <a class="dropdown-item" href="#" @click="selectBank(bank)">
                      {{ bank }}
                    </a>
                  </li>
                </ul>
              </div>
              <datalist id="bankList">
                <option v-for="bank in supportedBanks" :key="bank" :value="bank">
              </datalist>
              <div class="form-text" v-if="validation.standardizedBankName && validation.standardizedBankName !== formData.bankName">
                <i class="fas fa-check-circle text-success"></i>
                标准化为：{{ validation.standardizedBankName }}
              </div>
              <div class="invalid-feedback" v-if="!validation.bankNameValid && formData.bankName">
                银行名称无法识别，请从列表中选择
              </div>
            </div>
          </div>
          
          <!-- 验证结果显示 -->
          <div class="validation-result mt-3" v-if="showValidation">
            <div class="alert" :class="{
              'alert-success': validation.isValid,
              'alert-warning': !validation.isValid && validation.errors.length > 0,
              'alert-danger': !validation.isValid && !validation.cardNumberValid
            }">
              <div class="d-flex align-items-center mb-2">
                <i class="fas" :class="{
                  'fa-check-circle text-success': validation.isValid,
                  'fa-exclamation-triangle text-warning': !validation.isValid && validation.errors.length > 0,
                  'fa-times-circle text-danger': !validation.isValid && !validation.cardNumberValid
                }"></i>
                <strong class="ms-2">
                  {{ validation.isValid ? '验证通过' : '验证失败' }}
                </strong>
              </div>
              
              <div class="validation-details">
                <div class="row">
                  <div class="col-md-4">
                    <small class="text-muted">卡号验证：</small>
                    <span class="badge" :class="{
                      'bg-success': validation.cardNumberValid,
                      'bg-danger': !validation.cardNumberValid
                    }">
                      {{ validation.cardNumberValid ? '通过' : '失败' }}
                    </span>
                  </div>
                  <div class="col-md-4">
                    <small class="text-muted">银行名称：</small>
                    <span class="badge" :class="{
                      'bg-success': validation.bankNameValid,
                      'bg-danger': !validation.bankNameValid
                    }">
                      {{ validation.bankNameValid ? '通过' : '失败' }}
                    </span>
                  </div>
                  <div class="col-md-4" v-if="validation.detectedBank">
                    <small class="text-muted">银行匹配：</small>
                    <span class="badge" :class="{
                      'bg-success': validation.bankMatch,
                      'bg-warning': !validation.bankMatch
                    }">
                      {{ validation.bankMatch ? '匹配' : '不匹配' }}
                    </span>
                  </div>
                </div>
                
                <div class="mt-2" v-if="validation.errors.length > 0">
                  <small class="text-muted">错误信息：</small>
                  <ul class="mb-0 mt-1">
                    <li v-for="error in validation.errors" :key="error" class="small">
                      {{ error }}
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
          
          <div class="d-flex justify-content-between align-items-center mt-4">
            <button type="submit" class="btn btn-primary">
              <i class="fas fa-check me-2"></i>
              验证银行卡信息
            </button>
            
            <button type="button" class="btn btn-outline-secondary" @click="clearForm">
              <i class="fas fa-undo me-2"></i>
              重置
            </button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- 使用说明 -->
    <div class="card mt-4">
      <div class="card-header bg-light">
        <h6 class="mb-0">
          <i class="fas fa-info-circle me-2"></i>
          使用说明
        </h6>
      </div>
      <div class="card-body">
        <div class="row">
          <div class="col-md-6">
            <h6 class="text-primary">支持的验证功能：</h6>
            <ul class="list-unstyled">
              <li><i class="fas fa-check text-success me-2"></i>Luhn算法验证卡号格式</li>
              <li><i class="fas fa-check text-success me-2"></i>BIN码自动识别银行</li>
              <li><i class="fas fa-check text-success me-2"></i>银行名称标准化</li>
              <li><i class="fas fa-check text-success me-2"></i>银行与卡号匹配验证</li>
            </ul>
          </div>
          <div class="col-md-6">
            <h6 class="text-primary">支持的银行：</h6>
            <div class="small text-muted" style="max-height: 120px; overflow-y: auto;">
              <span v-for="(bank, index) in supportedBanks" :key="bank" class="badge bg-light text-dark me-1 mb-1">
                {{ bank }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { 
  validateBankCard, 
  getSupportedBanks, 
  formatCardNumber, 
  getBankByBIN 
} from '@/utils/bankCardValidator';

export default {
  name: 'BankCardValidator',
  data() {
    return {
      formData: {
        cardNumber: '',
        bankName: ''
      },
      validation: {
        isValid: false,
        cardNumberValid: false,
        bankNameValid: false,
        bankMatch: false,
        detectedBank: null,
        standardizedBankName: null,
        errors: []
      },
      supportedBanks: [],
      showValidation: false,
      detectedBank: null
    };
  },
  
  mounted() {
    this.supportedBanks = getSupportedBanks();
  },
  
  methods: {
    onCardNumberInput() {
      // 格式化显示
      const formatted = formatCardNumber(this.formData.cardNumber);
      if (formatted !== this.formData.cardNumber) {
        this.$nextTick(() => {
          this.formData.cardNumber = formatted;
        });
      }
      
      // 检测银行
      this.detectedBank = getBankByBIN(this.formData.cardNumber);
      
      // 自动填充银行名称
      if (this.detectedBank && !this.formData.bankName) {
        this.formData.bankName = this.detectedBank;
      }
      
      // 实时验证
      if (this.formData.cardNumber.replace(/\D/g, '').length >= 13) {
        this.validateCard();
      }
    },
    
    onBankNameInput() {
      // 实时验证
      if (this.formData.bankName.length >= 2) {
        this.validateCard();
      }
    },
    
    selectBank(bank) {
      this.formData.bankName = bank;
      this.validateCard();
    },
    
    validateCard() {
      if (!this.formData.cardNumber && !this.formData.bankName) {
        this.showValidation = false;
        return;
      }
      
      this.validation = validateBankCard(this.formData.cardNumber, this.formData.bankName);
      this.showValidation = true;
      
      // 触发验证结果事件
      this.$emit('validation-result', {
        ...this.validation,
        formData: { ...this.formData }
      });
    },
    
    clearForm() {
      this.formData = {
        cardNumber: '',
        bankName: ''
      };
      this.validation = {
        isValid: false,
        cardNumberValid: false,
        bankNameValid: false,
        bankMatch: false,
        detectedBank: null,
        standardizedBankName: null,
        errors: []
      };
      this.showValidation = false;
      this.detectedBank = null;
      
      this.$emit('validation-result', null);
    },
    
    // 供外部调用的验证方法
    validate() {
      this.validateCard();
      return this.validation;
    },
    
    // 设置表单数据
    setFormData(cardNumber, bankName) {
      this.formData.cardNumber = cardNumber || '';
      this.formData.bankName = bankName || '';
      this.validateCard();
    }
  },
  
  watch: {
    'formData.cardNumber'(newVal) {
      if (!newVal) {
        this.detectedBank = null;
      }
    }
  }
};
</script>

<style scoped>
.bank-card-validator {
  max-width: 800px;
  margin: 0 auto;
}

.validation-result {
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.validation-details .badge {
  font-size: 0.75em;
}

.dropdown-menu {
  max-height: 200px;
  overflow-y: auto;
}

.form-control.is-valid {
  border-color: #198754;
}

.form-control.is-invalid {
  border-color: #dc3545;
}

.alert {
  border-left: 4px solid;
}

.alert-success {
  border-left-color: #198754;
}

.alert-warning {
  border-left-color: #ffc107;
}

.alert-danger {
  border-left-color: #dc3545;
}
</style>